<script>
import vue from './main.js'

	/**
	 * 会话缓存
	 */
	const session = {
		get: function(key) {
			let val = sessionStorage.getItem(key);
			if(val != null) return JSON.parse(val);
		},
		set: function(key, val) {
			if(val != null) sessionStorage.setItem(key, JSON.stringify(val));
		},
		remove: function(key) {
			sessionStorage.removeItem(key)
		},
		clear: function() {
			sessionStorage.clear()
		},
		
		getUser: function() {
			return JSON.parse(sessionStorage.getItem('user')) || {}
		},
		setUser: function(user) {
			sessionStorage.setItem('user', JSON.stringify(user));
		}
	}
	
	/**
	 * 会话缓存
	 */
	const local = {
		get: function(key) {
			let val = localStorage.getItem(key);
			if(val != null) return JSON.parse(val);
		},
		set: function(key, val) {
			if(val != null) localStorage.setItem(key, JSON.stringify(val));
		},
		remove: function(key) {
			localStorage.removeItem(key)
		},
		clear: function() {
			localStorage.clear()
		},
		
		getUser: function() {
			return JSON.parse(localStorage.getItem('user')) || {}
		},
		setUser: function(user) {
			localStorage.setItem('user', JSON.stringify(user));
		}
	}

	const format = {
		
	/**
	 * 密码加密
	 * @param password
	 * @returns {string}
	 */
	encryPassword: function (password) {
		return hex_md5(password + md5Key)
	},		
		
	/**
	 * 10进制转62进制
	 * @param number
	 * @returns {string}
	 * @private
	 */
	tenTo62: function (number) {
		let chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ';
		let radix = chars.length;
		let arr = [];
		do {
			let mod = number % radix;
			number = (number - mod) / radix;
			arr.unshift(chars[mod]);
		} while (number);
		return arr.join('');
	},
		
		/**
		 * 文件大小格式化
		 * 大于1024KB显示MB
		 * 小于1024KB显示KB
		 */
		formatFileSize: function(value) {
			if(!value) return 0
			if(value < 1024 * 1024) return	Math.round((value / 1024) * 100) / 100 + "kb"
			else return Math.round((value / 1024 / 1024) * 100) / 100 + "mb"
		},
		
		
		/**
		 * 时长格式化
		 * @param value 例如：36000
		 * @returns {string} 例如：10:00:00
		 */		
		formatSecond: function(value) {
    value = value || 0;
    let second = parseInt(value, 10); // 秒
    let minute = 0; // 分
    let hour = 0; // 小时
    if (second >= 60) {
        // 当大于60秒时，才需要做转换
        minute = Math.floor(second / 60);
        second = Math.floor(second % 60);
        if (minute >= 60) {
            hour = Math.floor(minute / 60);
            minute = Math.floor(minute % 60);
        }
    } else {
        // 小于60秒时，直接显示，不需要处理
    }
    let result = "" + tool.PrefixInteger(second, 2) + "";
    // 拼上分钟
    result = "" + tool.PrefixInteger(minute, 2) + ":" + result;
    // 拼上小时
    result = "" + tool.PrefixInteger(hour, 2) + ":" + result;
    return result;			
		}
	}



	/**
	 * toast弹出框样式
	 */
	const toast = {
		success: {
			location: 'top',
			duration: 3000,
			toastStyle: { background: 'limegreen', minWidth: '20rem' }
		},
		fail: {
			location: 'top',
			duration: 4000,
			toastStyle: { background: '#ff5555', minWidth: '20rem' }
		},
		warn: {
			location: 'top',
			duration: 4000,
			toastStyle: { background: 'orange', minWidth: '20rem' }
		}
	}

	/**
	 * 常量
	 */
	const constant = {
		FILE_PURPOSE: {teacher: 1, course: 2, section: 3},
		FILE_URL: 'http://127.0.0.1:9000/file/static/',
		
		// redis前缀
		IMAGE_CODE: 'IMAGE_CODE-',
		USER_TOKEN: 'USER_TOKEN-',
	}

	/**
	 * 枚举
	 */	
	const enums = {
		CHARGE: [{key: 0, value: '免费'}, {key: 1, value: '收费'}],
		COURSE_LEVEL: [{key: 1, value: '初级'}, {key: 2, value: '中级'}, {key: 3, value: '高级'}],
		COURSE_STATUS: [{key: 0, value: '草稿'}, {key: 1, value: '发布'}],
		FILE_PURPOSE: [{key: 1, value: '讲师'}, {key: 2, value: '课程'}],
		
		getValue: function(val, vals) {
			for(let i = 0; i < vals.length; i++) {
				if(val === vals[i].key) return vals[i].value
			}
			return ''
		}
	}

	/**
	 * 数据校验
	 */	
	const validator = {
		require: function(value, text) {
			if(tool.isEmpty(value)) {
				vue.$toast(text + '不能为空', toast.fail)
				return false
			}
			return true
		},
		length: function (value, text, min, max) {
			if (tool.isEmpty(value)) {
				return true;
			}
			if (!tool.isLength(value, min, max)) {
				vue.$toast(text + "长度" + min + "~" + max + "位", toast.fail);
				return false;
			} else {
				return true
			}
		}
	}

	/**
	 * 工具类
	 */	
	const tool = {
		/**
		 * 空校验 null或""都返回true
		 */
		isEmpty: function (obj) {
			if ((typeof obj == 'string')) {
				return !obj || obj.replace(/\s+/g, "") == ""
			} else {
				return (!obj || JSON.stringify(obj) === "{}" || obj.length === 0);
			}
		},
		/**
		 * 长度校验
		 */
		isLength: function (str, min, max) {
			return $.trim(str).length >= min && $.trim(str).length <= max;
		},
		/**
		 * 格式化指定长度，前面补0
		 */
		PrefixInteger: function(num, length) {
			return (Array(length).join('0') + num).slice(-length);
		},
		/**
		 * 随机生成[len]长度的[radix]进制数
		 * @param len
		 * @param radix 默认62
		 * @returns {string}
		 */
		uuid: function (len, radix) {
			let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
			let uuid = [];
			radix = radix || chars.length;
	
			for (let i = 0; i < len; i++) {
				// |位运算符
				uuid[i] = chars[0 | Math.random() * radix];
			}
	
			return uuid.join('');
		},

	}

export default{
	session,
	local,
	toast,
	tool,
	constant,
	enums,
	format,
	validator
}
</script>

